package com.enation.app.javashop.consumer.job.execute.impl;

import com.enation.app.javashop.consumer.job.execute.EveryFiveMinExecute;
import com.enation.app.javashop.core.base.rabbitmq.AmqpExchange;
import com.enation.app.javashop.core.distribution.model.dos.DistributionDO;
import com.enation.app.javashop.core.distribution.model.vo.DistributionRelationshipVO;
import com.enation.app.javashop.core.distribution.service.DistributionManager;
import com.enation.app.javashop.framework.util.DateUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 分销关系处理任务
 */
@Service
public class DistributionRelationshipJob implements EveryFiveMinExecute {

    protected final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    private DistributionManager distributionManager;
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public void everyFiveMin() {
        // 查询所有的粉丝
        List<DistributionDO> distributionList = distributionManager.getAllFans();
        List<DistributionRelationshipVO> distributionRelationshipVOList = new ArrayList<>();
        if(distributionList != null && distributionList.size() > 0){
            for (DistributionDO distributionDO : distributionList) {
                try{
                    Long lv1ExpireTime = distributionDO.getLv1ExpireTime();
                    long currDate = DateUtil.getDateline();
                    if(currDate >= lv1ExpireTime){
                        distributionManager.removeLv1Relationship(distributionDO.getMemberId());

                        DistributionRelationshipVO lastDistributionRelationshipVO = distributionManager.buildDistributionRelationshipVO(distributionDO.getMemberId(), distributionDO.getMemberIdLv1()
                                , "团长解绑", 3,  "锁定到期自动解绑");
                        distributionRelationshipVOList.add(lastDistributionRelationshipVO);
                    }
                }catch (Exception e){
                    logger.error("清除粉丝关系报错", e);
                }
            }
            if(!CollectionUtils.isEmpty(distributionRelationshipVOList)){
                // 保存历史团长信息
                amqpTemplate.convertAndSend(AmqpExchange.DISTIRBUTION_BINDING_MESSAGE,
                        AmqpExchange.DISTIRBUTION_BINDING_MESSAGE + "_ROUTING",
                        distributionRelationshipVOList);
            }
        }
    }
}
